{% extends "base.html" %}

{% block title %}RTSP截图 - {{ project.name }} - AI模型训练平台{% endblock %}

{% block extra_css %}
<style>
.capture-card {
    transition: transform 0.2s;
}

.capture-card:hover {
    transform: scale(1.02);
}

.status-indicator {
    display: inline-block;
    width: 10px;
    height: 10px;
    border-radius: 50%;
    margin-right: 5px;
}

.status-running {
    background-color: #28a745;
}

.status-stopped {
    background-color: #dc3545;
}

.status-pending {
    background-color: #ffc107;
}
</style>
{% endblock %}

{% block content %}
<nav aria-label="breadcrumb">
    <ol class="breadcrumb">
        <li class="breadcrumb-item"><a href="{{ url_for('main.index') }}">项目列表</a></li>
        <li class="breadcrumb-item"><a href="{{ url_for('main.project_detail', project_id=project.id) }}">{{ project.name }}</a></li>
        <li class="breadcrumb-item"><a href="{{ url_for('main.project_images', project_id=project.id) }}">图片管理</a></li>
        <li class="breadcrumb-item active" aria-current="page">RTSP截图</li>
    </ol>
</nav>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h1>AI模型训练平台 - RTSP截图</h1>
</div>

<ul class="nav nav-tabs mb-4">
    <li class="nav-item">
        <a class="nav-link" href="{{ url_for('main.project_detail', project_id=project.id) }}">
            <i class="fas fa-tachometer-alt"></i> 项目概览
        </a>
    </li>
    <li class="nav-item">
        <a class="nav-link" href="{{ url_for('main.project_images', project_id=project.id) }}">
            <i class="fas fa-images"></i> 图片管理
        </a>
    </li>
    <li class="nav-item">
        <a class="nav-link active" href="{{ url_for('main.rtsp_capture', project_id=project.id) }}">
            <i class="fas fa-video"></i> RTSP截图
        </a>
    </li>
    <li class="nav-item">
        <a class="nav-link" href="{{ url_for('main.annotate', project_id=project.id) }}">
            <i class="fas fa-object-group"></i> 图片标注
        </a>
    </li>
    <li class="nav-item">
        <a class="nav-link" href="{{ url_for('main.project_dataset', project_id=project.id) }}">
            <i class="fas fa-database"></i> 数据集划分
        </a>
    </li>
    <li class="nav-item">
        <a class="nav-link" href="{{ url_for('main.project_train', project_id=project.id) }}">
            <i class="fas fa-brain"></i> 模型训练
        </a>
    </li>
    <li class="nav-item">
        <a class="nav-link" href="{{ url_for('main.project_export', project_id=project.id) }}">
            <i class="fas fa-file-export"></i> 模型导出
        </a>
    </li>
</ul>

<div class="row">
    <div class="col-md-8">
        <div class="card mb-4">
            <div class="card-header">
                <div class="d-flex justify-content-between align-items-center">
                    <span>RTSP截图</span>
                    <button class="btn btn-sm btn-primary" type="button" data-bs-toggle="collapse" data-bs-target="#rtspHelp" aria-expanded="false" aria-controls="rtspHelp">
                        <i class="fas fa-question-circle"></i> 帮助
                    </button>
                </div>
            </div>
            <div class="card-body">
                <div class="collapse" id="rtspHelp">
                    <div class="alert alert-info">
                        <h6>RTSP截图说明：</h6>
                        <ul>
                            <li>输入RTSP地址，设置截图间隔和总数量开始截图</li>
                            <li>截图会自动保存到当前项目中</li>
                            <li>可以通过停止按钮中断截图过程</li>
                        </ul>
                    </div>
                </div>
                
                <form id="rtspForm">
                    <div class="mb-3">
                        <label for="rtspUrl" class="form-label">RTSP地址</label>
                        <input type="text" class="form-control" id="rtspUrl" placeholder="rtsp://username:password@ip:port/path" required>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="interval" class="form-label">截图间隔（秒）</label>
                                <input type="number" class="form-control" id="interval" min="1" max="3600" value="5" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="maxCount" class="form-label">总截图数量</label>
                                <input type="number" class="form-control" id="maxCount" min="1" max="10000" value="10" required>
                            </div>
                        </div>
                    </div>
                    
                    <button type="submit" class="btn btn-primary" id="startRtspBtn">
                        <i class="fas fa-play"></i> 开始截图
                    </button>
                    <button type="button" class="btn btn-danger" id="stopRtspBtn" disabled>
                        <i class="fas fa-stop"></i> 停止截图
                    </button>
                </form>
            </div>
        </div>
        
        <div class="card mb-4">
            <div class="card-header">
                <span>ONVIF摄像头截图</span>
                <button class="btn btn-sm btn-primary" type="button" data-bs-toggle="collapse" data-bs-target="#onvifHelp" aria-expanded="false" aria-controls="onvifHelp">
                    <i class="fas fa-question-circle"></i> 帮助
                </button>
            </div>
            <div class="card-body">
                <div class="collapse" id="onvifHelp">
                    <div class="alert alert-info">
                        <h6>ONVIF摄像头截图说明：</h6>
                        <ul>
                            <li>点击"查找摄像头"按钮发现局域网内的ONVIF设备</li>
                            <li>选择设备并输入用户名密码</li>
                            <li>选择摄像头通道，设置截图间隔和总数量开始截图</li>
                        </ul>
                    </div>
                </div>
                
                <div class="mb-3">
                    <button class="btn btn-info" id="discoverBtn">
                        <i class="fas fa-search"></i> 查找摄像头
                    </button>
                </div>
                
                <div id="onvifDevices" class="mb-3" style="display: none;">
                    <h6>发现的设备：</h6>
                    <div id="devicesList"></div>
                </div>
                
                <div id="onvifFormContainer" style="display: none;">
                    <form id="onvifLoginForm">
                        <input type="hidden" id="deviceIp">
                        <input type="hidden" id="devicePort">
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="onvifUsername" class="form-label">用户名</label>
                                    <input type="text" class="form-control" id="onvifUsername" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="onvifPassword" class="form-label">密码</label>
                                    <input type="password" class="form-control" id="onvifPassword" required>
                                </div>
                            </div>
                        </div>
                        
                        <button type="submit" class="btn btn-secondary">
                            <i class="fas fa-sign-in-alt"></i> 登录设备
                        </button>
                    </form>
                </div>
                
                <div id="profilesContainer" style="display: none;">
                    <h6>摄像头通道：</h6>
                    <div id="profilesList" class="mb-3"></div>
                    
                    <form id="onvifCaptureForm">
                        <input type="hidden" id="selectedProfile">
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="onvifInterval" class="form-label">截图间隔（秒）</label>
                                    <input type="number" class="form-control" id="onvifInterval" min="1" max="3600" value="5" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="onvifMaxCount" class="form-label">总截图数量</label>
                                    <input type="number" class="form-control" id="onvifMaxCount" min="1" max="10000" value="10" required>
                                </div>
                            </div>
                        </div>
                        
                        <button type="submit" class="btn btn-primary" id="startOnvifBtn">
                            <i class="fas fa-play"></i> 开始截图
                        </button>
                        <button type="button" class="btn btn-danger" id="stopOnvifBtn" disabled>
                            <i class="fas fa-stop"></i> 停止截图
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-4">
        <div class="card">
            <div class="card-header">
                截图状态
            </div>
            <div class="card-body">
                <div class="mb-3">
                    <h6>RTSP截图状态</h6>
                    <div id="rtspStatus">
                        <span class="status-indicator status-stopped"></span>
                        <span>未运行</span>
                    </div>
                    <div class="mt-2">
                        <small>已截图: <span id="rtspCapturedCount">0</span>/<span id="rtspMaxCount">0</span></small>
                    </div>
                </div>
                
                <div class="mb-3">
                    <h6>ONVIF截图状态</h6>
                    <div id="onvifStatus">
                        <span class="status-indicator status-stopped"></span>
                        <span>未运行</span>
                    </div>
                    <div class="mt-2">
                        <small>已截图: <span id="onvifCapturedCount">0</span>/<span id="onvifMaxCount">0</span></small>
                    </div>
                </div>
                
                <div class="mt-4">
                    <button class="btn btn-sm btn-outline-primary" id="refreshStatusBtn">
                        <i class="fas fa-sync"></i> 刷新状态
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    const projectId = {{ project.id }};
    
    // RTSP截图功能
    const rtspForm = document.getElementById('rtspForm');
    const startRtspBtn = document.getElementById('startRtspBtn');
    const stopRtspBtn = document.getElementById('stopRtspBtn');
    
    // ONVIF功能
    const discoverBtn = document.getElementById('discoverBtn');
    const onvifDevices = document.getElementById('onvifDevices');
    const devicesList = document.getElementById('devicesList');
    const onvifFormContainer = document.getElementById('onvifFormContainer');
    const onvifLoginForm = document.getElementById('onvifLoginForm');
    const profilesContainer = document.getElementById('profilesContainer');
    const profilesList = document.getElementById('profilesList');
    const onvifCaptureForm = document.getElementById('onvifCaptureForm');
    const startOnvifBtn = document.getElementById('startOnvifBtn');
    const stopOnvifBtn = document.getElementById('stopOnvifBtn');
    
    // 状态显示元素
    const rtspStatus = document.getElementById('rtspStatus');
    const rtspCapturedCount = document.getElementById('rtspCapturedCount');
    const rtspMaxCount = document.getElementById('rtspMaxCount');
    const onvifStatus = document.getElementById('onvifStatus');
    const onvifCapturedCount = document.getElementById('onvifCapturedCount');
    const onvifMaxCount = document.getElementById('onvifMaxCount');
    const refreshStatusBtn = document.getElementById('refreshStatusBtn');
    
    // RTSP截图表单提交
    rtspForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const rtspUrl = document.getElementById('rtspUrl').value;
        const interval = parseInt(document.getElementById('interval').value);
        const maxCount = parseInt(document.getElementById('maxCount').value);
        
        startRtspBtn.disabled = true;
        startRtspBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 启动中...';
        
        fetch(`/api/project/${projectId}/rtsp/start`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                rtsp_url: rtspUrl,
                interval: interval,
                max_count: maxCount
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                stopRtspBtn.disabled = false;
                updateRtspStatus();
            } else {
                alert('启动失败: ' + data.message);
                startRtspBtn.disabled = false;
                startRtspBtn.innerHTML = '<i class="fas fa-play"></i> 开始截图';
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('启动截图时发生错误');
            startRtspBtn.disabled = false;
            startRtspBtn.innerHTML = '<i class="fas fa-play"></i> 开始截图';
        });
    });
    
    // 停止RTSP截图
    stopRtspBtn.addEventListener('click', function() {
        stopRtspBtn.disabled = true;
        stopRtspBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 停止中...';
        
        fetch(`/api/project/${projectId}/rtsp/stop`, {
            method: 'POST'
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                startRtspBtn.disabled = false;
                stopRtspBtn.disabled = true;
                stopRtspBtn.innerHTML = '<i class="fas fa-stop"></i> 停止截图';
                updateRtspStatus();
            } else {
                alert('停止失败: ' + data.message);
                stopRtspBtn.disabled = false;
                stopRtspBtn.innerHTML = '<i class="fas fa-stop"></i> 停止截图';
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('停止截图时发生错误');
            stopRtspBtn.disabled = false;
            stopRtspBtn.innerHTML = '<i class="fas fa-stop"></i> 停止截图';
        });
    });
    
    // 查找ONVIF设备
    discoverBtn.addEventListener('click', function() {
        discoverBtn.disabled = true;
        discoverBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 搜索中...';
        
        fetch(`/api/onvif/discover`, {
            method: 'GET'
        })
        .then(response => response.json())
        .then(data => {
            discoverBtn.disabled = false;
            discoverBtn.innerHTML = '<i class="fas fa-search"></i> 查找摄像头';
            
            if (data.success) {
                if (data.devices && data.devices.length > 0) {
                    onvifDevices.style.display = 'block';
                    devicesList.innerHTML = '';
                    
                    data.devices.forEach(device => {
                        const deviceDiv = document.createElement('div');
                        deviceDiv.className = 'card mb-2';
                        deviceDiv.innerHTML = `
                            <div class="card-body">
                                <h6 class="card-title">${device.name || '未知设备'}</h6>
                                <p class="card-text">
                                    IP: ${device.ip}<br>
                                    端口: ${device.port}
                                </p>
                                <button class="btn btn-sm btn-primary select-device-btn" 
                                        data-ip="${device.ip}" 
                                        data-port="${device.port}">
                                    选择设备
                                </button>
                            </div>
                        `;
                        devicesList.appendChild(deviceDiv);
                    });
                    
                    // 绑定选择设备按钮事件
                    document.querySelectorAll('.select-device-btn').forEach(btn => {
                        btn.addEventListener('click', function() {
                            const ip = this.getAttribute('data-ip');
                            const port = this.getAttribute('data-port');
                            
                            document.getElementById('deviceIp').value = ip;
                            document.getElementById('devicePort').value = port;
                            
                            onvifDevices.style.display = 'none';
                            onvifFormContainer.style.display = 'block';
                        });
                    });
                } else {
                    alert('未发现ONVIF设备');
                }
            } else {
                alert('搜索失败: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('搜索设备时发生错误');
            discoverBtn.disabled = false;
            discoverBtn.innerHTML = '<i class="fas fa-search"></i> 查找摄像头';
        });
    });
    
    // ONVIF登录表单提交
    onvifLoginForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const deviceIp = document.getElementById('deviceIp').value;
        const devicePort = document.getElementById('devicePort').value;
        const username = document.getElementById('onvifUsername').value;
        const password = document.getElementById('onvifPassword').value;
        
        const loginBtn = onvifLoginForm.querySelector('button[type="submit"]');
        loginBtn.disabled = true;
        loginBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 登录中...';
        
        fetch(`/api/onvif/${deviceIp}/${devicePort}/profiles`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                username: username,
                password: password
            })
        })
        .then(response => response.json())
        .then(data => {
            loginBtn.disabled = false;
            loginBtn.innerHTML = '<i class="fas fa-sign-in-alt"></i> 登录设备';
            
            if (data.success) {
                if (data.profiles && data.profiles.length > 0) {
                    profilesContainer.style.display = 'block';
                    profilesList.innerHTML = '';
                    
                    data.profiles.forEach(profile => {
                        const profileDiv = document.createElement('div');
                        profileDiv.className = 'card mb-2';
                        profileDiv.innerHTML = `
                            <div class="card-body">
                                <h6 class="card-title">${profile.name}</h6>
                                <p class="card-text">
                                    Token: ${profile.token}
                                </p>
                                <button class="btn btn-sm btn-primary select-profile-btn" 
                                        data-token="${profile.token}">
                                    选择通道
                                </button>
                            </div>
                        `;
                        profilesList.appendChild(profileDiv);
                    });
                    
                    // 绑定选择通道按钮事件
                    document.querySelectorAll('.select-profile-btn').forEach(btn => {
                        btn.addEventListener('click', function() {
                            const token = this.getAttribute('data-token');
                            document.getElementById('selectedProfile').value = token;
                        });
                    });
                } else {
                    alert('该设备没有可用的摄像头通道');
                }
            } else {
                alert('登录失败: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('登录设备时发生错误');
            loginBtn.disabled = false;
            loginBtn.innerHTML = '<i class="fas fa-sign-in-alt"></i> 登录设备';
        });
    });
    
    // ONVIF截图表单提交
    onvifCaptureForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const deviceIp = document.getElementById('deviceIp').value;
        const devicePort = document.getElementById('devicePort').value;
        const username = document.getElementById('onvifUsername').value;
        const password = document.getElementById('onvifPassword').value;
        const profileToken = document.getElementById('selectedProfile').value;
        const interval = parseInt(document.getElementById('onvifInterval').value);
        const maxCount = parseInt(document.getElementById('onvifMaxCount').value);
        
        if (!profileToken) {
            alert('请先选择摄像头通道');
            return;
        }
        
        startOnvifBtn.disabled = true;
        startOnvifBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 启动中...';
        
        fetch(`/api/project/${projectId}/onvif/start`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                device_ip: deviceIp,
                device_port: devicePort,
                username: username,
                password: password,
                profile_token: profileToken,
                interval: interval,
                max_count: maxCount
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                stopOnvifBtn.disabled = false;
                updateOnvifStatus(profileToken);
            } else {
                alert('启动失败: ' + data.message);
                startOnvifBtn.disabled = false;
                startOnvifBtn.innerHTML = '<i class="fas fa-play"></i> 开始截图';
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('启动截图时发生错误');
            startOnvifBtn.disabled = false;
            startOnvifBtn.innerHTML = '<i class="fas fa-play"></i> 开始截图';
        });
    });
    
    // 停止ONVIF截图
    stopOnvifBtn.addEventListener('click', function() {
        const profileToken = document.getElementById('selectedProfile').value;
        
        stopOnvifBtn.disabled = true;
        stopOnvifBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 停止中...';
        
        fetch(`/api/project/${projectId}/onvif/stop`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                profile_token: profileToken
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                startOnvifBtn.disabled = false;
                stopOnvifBtn.disabled = true;
                stopOnvifBtn.innerHTML = '<i class="fas fa-stop"></i> 停止截图';
                updateOnvifStatus(profileToken);
            } else {
                alert('停止失败: ' + data.message);
                stopOnvifBtn.disabled = false;
                stopOnvifBtn.innerHTML = '<i class="fas fa-stop"></i> 停止截图';
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('停止截图时发生错误');
            stopOnvifBtn.disabled = false;
            stopOnvifBtn.innerHTML = '<i class="fas fa-stop"></i> 停止截图';
        });
    });
    
    // 刷新状态
    refreshStatusBtn.addEventListener('click', function() {
        updateRtspStatus();
        if (document.getElementById('selectedProfile').value) {
            updateOnvifStatus(document.getElementById('selectedProfile').value);
        }
    });
    
    // 更新RTSP状态
    function updateRtspStatus() {
        fetch(`/api/project/${projectId}/rtsp/status`)
        .then(response => response.json())
        .then(data => {
            if (data.status) {
                // 更新状态显示
                if (data.status.running) {
                    rtspStatus.innerHTML = '<span class="status-indicator status-running"></span> 运行中';
                    startRtspBtn.disabled = true;
                    stopRtspBtn.disabled = false;
                } else {
                    rtspStatus.innerHTML = '<span class="status-indicator status-stopped"></span> 已停止';
                    startRtspBtn.disabled = false;
                    stopRtspBtn.disabled = true;
                }
                
                // 更新计数
                rtspCapturedCount.textContent = data.status.captured_count || 0;
                rtspMaxCount.textContent = data.status.max_count || 0;
            } else {
                rtspStatus.innerHTML = '<span class="status-indicator status-stopped"></span> 未运行';
                startRtspBtn.disabled = false;
                stopRtspBtn.disabled = true;
                rtspCapturedCount.textContent = '0';
                rtspMaxCount.textContent = '0';
            }
        })
        .catch(error => {
            console.error('Error:', error);
        });
    }
    
    // 更新ONVIF状态
    function updateOnvifStatus(profileToken) {
        fetch(`/api/project/${projectId}/onvif/status`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                profile_token: profileToken
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.status) {
                // 更新状态显示
                if (data.status.running) {
                    onvifStatus.innerHTML = '<span class="status-indicator status-running"></span> 运行中';
                    startOnvifBtn.disabled = true;
                    stopOnvifBtn.disabled = false;
                } else {
                    onvifStatus.innerHTML = '<span class="status-indicator status-stopped"></span> 已停止';
                    startOnvifBtn.disabled = false;
                    stopOnvifBtn.disabled = true;
                }
                
                // 更新计数
                onvifCapturedCount.textContent = data.status.captured_count || 0;
                onvifMaxCount.textContent = data.status.max_count || 0;
            } else {
                onvifStatus.innerHTML = '<span class="status-indicator status-stopped"></span> 未运行';
                startOnvifBtn.disabled = false;
                stopOnvifBtn.disabled = true;
                onvifCapturedCount.textContent = '0';
                onvifMaxCount.textContent = '0';
            }
        })
        .catch(error => {
            console.error('Error:', error);
        });
    }
    
    // 定期更新状态
    setInterval(function() {
        updateRtspStatus();
        if (document.getElementById('selectedProfile').value) {
            updateOnvifStatus(document.getElementById('selectedProfile').value);
        }
    }, 5000); // 每5秒更新一次状态
});
</script>
{% endblock %}